package com.neuedu.it.mylink.controller;

import com.neuedu.it.mylink.controller.vo.Result;
import com.neuedu.it.mylink.dao.UserDao;
import com.neuedu.it.mylink.entity.User;
import com.neuedu.it.mylink.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/users")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String name,String pwd){
        User user= userService.login(name,pwd);
        if(user==null){
            return new Result(4001,"用户名或密码错误",null);
        }else{
            user.setPwd(null);
            //制作JWT凭证
            Map<String, Object> claims = new HashMap<>();
            claims.put("user", user);

            String jwt = Jwts.builder()
                    .setClaims(claims)//压缩用户信息到jwt
                    .setSubject(user.getId()+"")//设置jwt主键
                    .setIssuedAt(new Date())//设置jwt签发时间
                    .setExpiration(new Date(System.currentTimeMillis() + 1*60*60*1000))//设置jwt过期时间（1小时)
                    .signWith(SignatureAlgorithm.HS256, "123456")//设置jwt加密算法和密钥
                    .compact();

            Map<String,Object> data=new HashMap<>();
            data.put("user", user);
            data.put("jwttoken",jwt);
            return new Result(2000,"登录成功",data);
        }
    }
    @PostMapping("/")
    public Result reg(@RequestBody  User user){
       userService.register(user);
        return new Result(2000,"注册成功",null);
    }

}
